import React, { useState, useRef } from 'react'
// 🔧 修改：使用真实的 API，而不是 mockApi
import { uploadImage } from '../../utils/api'

export default function UploadModule({ onBack, onStatsUpdate }) {
  const [aiEnabled, setAiEnabled] = useState(true)
  const [uploading, setUploading] = useState(false)
  const [uploadedImages, setUploadedImages] = useState([])
  const [dragActive, setDragActive] = useState(false)
  const fileInputRef = useRef(null)

  // 处理文件上传
  async function handleFiles(files) {
    if (!files || files.length === 0) return

    setUploading(true)
    const newImages = []

    try {
      for (const file of files) {
        // 读取文件为 DataURL
        const dataUrl = await fileToDataUrl(file)
        
        // 🔧 修改：使用新的 uploadImage API
        const result = await uploadImage({
          name: file.name,
          dataUrl: dataUrl,
          aiEnabled: aiEnabled
        })

        newImages.push({
          id: result.id,
          name: result.name || file.name,
          dataUrl: result.filepath ? `http://localhost:3000${result.filepath}` : dataUrl,
          tags: result.tags || [],
          description: result.description || '',
          detections: result.detections || [],
          confidence: result.detections && result.detections.length > 0 
            ? result.detections.reduce((sum, d) => sum + d.confidence, 0) / result.detections.length 
            : 0,
          aiProcessed: result.aiProcessed || false
        })
      }

      setUploadedImages(prev => [...newImages, ...prev])
      
      // 更新统计信息
      if (onStatsUpdate) {
        onStatsUpdate()
      }

      // 显示成功消息
      alert(`成功上传 ${newImages.length} 张图片！`)
    } catch (err) {
      console.error('上传失败:', err)
      alert('上传失败: ' + err.message)
    } finally {
      setUploading(false)
    }
  }

  // 文件转 DataURL
  function fileToDataUrl(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = () => resolve(reader.result)
      reader.onerror = reject
      reader.readAsDataURL(file)
    })
  }

  // 拖拽处理
  function handleDrag(e) {
    e.preventDefault()
    e.stopPropagation()
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true)
    } else if (e.type === 'dragleave') {
      setDragActive(false)
    }
  }

  function handleDrop(e) {
    e.preventDefault()
    e.stopPropagation()
    setDragActive(false)

    const files = Array.from(e.dataTransfer.files).filter(f => 
      f.type.startsWith('image/')
    )
    
    if (files.length > 0) {
      handleFiles(files)
    }
  }

  // 文件选择
  function handleFileInput(e) {
    const files = Array.from(e.target.files)
    handleFiles(files)
    e.target.value = '' // 重置输入
  }

  // 删除上传的图片
  function handleRemove(id) {
    setUploadedImages(prev => prev.filter(img => img.id !== id))
  }

  return (
    <div className="upload-module">
      {/* 页面标题 */}
      <div className="card">
        <div className="card-header">
          <div className="section-title">
            <span className="section-icon">📤</span>
            <div>
              <h3 className="card-title">智能上传</h3>
              <p className="card-subtitle">上传叶片图片，AI 自动识别缺陷并生成标签</p>
            </div>
          </div>
          <button className="back-btn" onClick={onBack}>
            ← 返回
          </button>
        </div>

        {/* AI 功能开关 */}
        <div className="ai-toggle">
          <label className="toggle-switch">
            <input
              type="checkbox"
              checked={aiEnabled}
              onChange={(e) => setAiEnabled(e.target.checked)}
            />
            <span className="toggle-slider"></span>
          </label>
          <span className="toggle-label">
            {aiEnabled ? '🤖 AI 智能处理已启用' : '📁 普通上传模式'}
          </span>
        </div>

        {/* AI 功能说明 */}
        {aiEnabled && (
          <div className="ai-features">
            <div className="feature-tag">
              <span className="feature-icon">🎯</span>
              <span>自动缺陷检测</span>
            </div>
            <div className="feature-tag">
              <span className="feature-icon">🏷️</span>
              <span>智能标签生成</span>
            </div>
            <div className="feature-tag">
              <span className="feature-icon">📝</span>
              <span>AI 描述生成</span>
            </div>
            <div className="feature-tag">
              <span className="feature-icon">💾</span>
              <span>向量化存储</span>
            </div>
          </div>
        )}

        {/* 上传区域 */}
        <div
          className={`upload-drop-zone ${dragActive ? 'active' : ''} ${uploading ? 'uploading' : ''}`}
          onDragEnter={handleDrag}
          onDragLeave={handleDrag}
          onDragOver={handleDrag}
          onDrop={handleDrop}
          onClick={() => !uploading && fileInputRef.current?.click()}
        >
          <input
            ref={fileInputRef}
            type="file"
            multiple
            accept="image/*"
            style={{ display: 'none' }}
            onChange={handleFileInput}
            disabled={uploading}
          />
          
          {uploading ? (
            <div className="upload-status">
              <div className="loading-spinner"></div>
              <p className="upload-text">正在上传处理中...</p>
              <p className="upload-hint">
                {aiEnabled ? 'AI 正在分析图片，请稍候' : '正在保存图片'}
              </p>
            </div>
          ) : (
            <div className="upload-placeholder">
              <div className="upload-icon">📤</div>
              <p className="upload-text">拖拽图片到此处，或点击选择文件</p>
              <p className="upload-hint">支持 JPG、PNG、BMP 格式 · 可批量上传</p>
              <button className="upload-btn" onClick={(e) => {
                e.stopPropagation()
                fileInputRef.current?.click()
              }}>
                <span>📁</span>
                <span>选择文件</span>
              </button>
            </div>
          )}
        </div>
      </div>

      {/* 上传结果展示 */}
      {uploadedImages.length > 0 && (
        <div className="card">
          <div className="results-header">
            <h3 className="results-title">
              <span>✅</span>
              <span>上传成功</span>
              <span className="results-count">{uploadedImages.length} 张</span>
            </h3>
            <div className="results-actions">
              <button
                className="btn-clear"
                onClick={() => setUploadedImages([])}
              >
                清空列表
              </button>
            </div>
          </div>

          <div className="uploaded-images-grid">
            {uploadedImages.map((img) => (
              <div key={img.id} className="uploaded-image-card">
                <div className="image-preview">
                  <img src={img.dataUrl} alt={img.name} />
                  {img.aiProcessed && (
                    <div className="ai-badge">🤖 AI</div>
                  )}
                </div>
                
                <div className="image-info">
                  <h4 className="image-name">{img.name}</h4>
                  
                  {img.description && (
                    <p className="image-description">{img.description}</p>
                  )}
                  
                  {img.tags && img.tags.length > 0 && (
                    <div className="image-tags">
                      {img.tags.map((tag, idx) => (
                        <span key={idx} className="image-tag">
                          {tag}
                        </span>
                      ))}
                    </div>
                  )}
                  
                  {img.confidence > 0 && (
                    <div className="image-confidence">
                      <span className="confidence-label">置信度:</span>
                      <span className="confidence-value">
                        {(img.confidence * 100).toFixed(1)}%
                      </span>
                    </div>
                  )}
                </div>
                
                <button
                  className="remove-btn"
                  onClick={() => handleRemove(img.id)}
                  title="从列表中移除"
                >
                  ✕
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 使用提示 */}
      <div className="card info-card">
        <div className="info-header">
          <span className="info-icon">💡</span>
          <h4>使用提示</h4>
        </div>
        <ul className="info-list">
          <li>开启 AI 模式后，系统会自动分析图片中的缺陷类型并生成标签</li>
          <li>支持批量上传，系统会依次处理每张图片</li>
          <li>AI 处理的图片会自动保存到向量数据库，支持相似性搜索</li>
          <li>上传的图片会自动添加时间戳和元数据信息</li>
        </ul>
      </div>
    </div>
  )
}
